var get=require('../../../utils/getRequest');
var post=require('../../../utils/postRequest');
const api= require('../../../utils/api')
const mqtt = require('../../../utils/mqtt')
let client=null;
let ctx
Page({
  data: {
      deviceSn:null,
      connectFlag:false,
      TX:'',///TX/LR90000000001
      RX:'',///RX/LR90000000001
      productList:[],
      deviceMsg:null,
      sheetShow:false,
      sheetActions:[],
      textRevData: '',
      productOptions:[], 
      popupShow:false,
      note:null,
      fieldValue: '',
      gridList:[],
        index:0
  },
  onLoad(options) {
    var deviceSn=options.deviceSn;
      ctx = this
      const lastFourChars = deviceSn.substr(deviceSn.length - 8);
    var TX='/TX/LR900'+lastFourChars;
    var RX='/RX/LR900'+lastFourChars;
    console.log(lastFourChars); 
      ctx = this
      ctx.setData({
        deviceSn:deviceSn,
        TX:TX,
        RX:RX
      });     
      this.initMqtt();
      get.getRequest(null,api.getAllProductList,{}).then(res=>{
            ctx.setData({productList:res.data});
            ctx.getDevice();
      });
  },
  getDevice(){
    var data={deviceSn:ctx.data.deviceSn}
    get.getRequest(null,api.getDeviceByDeviceSn,data).then(res=>{
     ctx.setData({deviceMsg:res.data});
     ctx.initGrids();
     ctx.setProductOptions();
     ctx.initSheetActions();
    });
  },
  initSheetActions(){
    var deviceMsg=this.data.deviceMsg;
    var gridNumber=deviceMsg.gridNumber;
    var sheetActions=[];
    for(var i=1;i<=gridNumber;i++){
      sheetActions.push({id:"0"+i,name:"第"+i+"格子"});
    }
    this.setData({sheetActions:sheetActions})
  },
  initGrids(){
    var deviceMsg=this.data.deviceMsg;
    var gridNumber=deviceMsg.gridNumber;
    var gridList=[];
    console.log("格子数："+gridNumber);
    for(var i=1;i<=gridNumber;i++){
      var name="第"+i+"格";
      var note="选择服务状态";
      var str="";
      if(i<10) {str="grid0"+i+"ProductId";}
      else{str="grid"+i+"ProductId";}
      var obj=deviceMsg[str].split(",");
      var dictname=this.dictName(obj[0]);
      var productName=this.productName(obj[1]);
      name=name+"("+dictname+"/"+productName+")"
      gridList.push({name:name,note:note});
    }
    console.log("初始化：",gridList);
    this.setData({gridList:gridList});
  },
  setProductOptions(){
    var gridList=ctx.data.gridList;
    var deviceMsg=ctx.data.deviceMsg;
    var productOptions=[{label:'正常服务',value:'1',},{label:'停止服务',value:'2',}];
    for(var i=0;i<gridList.length;i++){
      var index=i+1;
      var name="";
      if(index<10){name="grid0"+index+"StateType";} 
      else{name="grid"+index+"StateType";} 
      var value=deviceMsg[name];
      console.log("值："+value);
      for(var j=0;j<productOptions.length;j++){
        console.log("值2："+productOptions[j].value);
        if(productOptions[j].value==value){
          gridList[i].note=productOptions[j].label;
        }
      }
    }    
    ctx.setData({
              productOptions:productOptions,
              gridList:gridList
            });
  },
  dictName(StateType){
      if(StateType=="1"){
        return '出售'
      }else if(StateType=="2"){
        return '出租'
      }
  },
  productName(ProductId){
    var productList=this.data.productList;
    for(var i=0;i<productList.length;i++){
      if(productList[i].productId==ProductId){
        return productList[i].productName;
      }
    }
  },
  saveRepairFlag(){
    var data={
      deviceSn:this.data.deviceSn,
      repairFlag: 'N'
    }
    wx.showLoading({title:'保存处理中'});
    get.getRequest(null,api.saveDevcieRepairFlag,data).then(res=>{
      wx.showModal({
        title: '提示信息',
        showCancel:false,
        content: res.msg
      })
    }).finally(res=>{
      wx.hideLoading();
    })
  },
  showCascader(e) {
    console.log(e);
    var index=e.currentTarget.dataset.index;
    this.setData({ popupShow: true,index:index });
  },
  onPick(e) {
    console.log(e.detail);
  },
  onChange(e) {
    console.log("------------------------");
    console.log(e);
    const { selectedOptions, value } = e.detail;
    
    var note=selectedOptions.map((item) => item.label).join('/');
    var index=this.data.index;
    var gridList=this.data.gridList;
    gridList[index].note=note;
    var data={
      index:index,
      deviceSn:ctx.data.deviceSn,
      stateType:selectedOptions[0].value
    }
    console.log(data)
    wx.showLoading({title:'保存处理中'});
    get.getRequest(null,api.saveDevcieGridState,data).then(res=>{
      if(res.code==200){
        ctx.setData({gridList:gridList});
        wx.showModal({
          title: '提示信息',
          showCancel:false,
          content: res.msg
        })
      }else{
        wx.showModal({
          title: '提示信息',
          showCancel:false,
          content: res.msg
        })
      }
    }).finally(res=>{
      wx.hideLoading();
    })
    

    /* this.setData({
      fieldValue:value,
      note: selectedOptions.map((item) => item.label).join('/'),
    }); */
  },
  onSheetSelect(e){
    var index=e.detail.id;
    var commd='';
    if(index<10){commd='{\"lock\":\"0'+index+'\"'+'}';}
    else{commd='{\"lock\":\"'+index+'\"'+'}';}
    console.log("commd======"+commd)
    client.publish(ctx.data.RX, commd);
  },
  showSheet(){
    this.setData({sheetShow:true})
    },
  onSheetClose(){
      this.setData({sheetShow:false})
    },
  onShow() {
  },
  initMqtt() {
    var url="wxs:device.x-washer.com/mqtt";
    console.log("服务器地址："+url);
    let randomNum = Math.floor(Math.random() * 100000000000)
    // 连接选项
    const options = {
      connectTimeout: 4000, // 超时时间
      // 认证信息 按自己需求填写
      clientId: 'wx'+randomNum,
      username: 'x-washer01',
      password: '123456Qwe',
    }
     var that = this;
    if(!client){
      client=null
    }
    //client = mqtt.connect('wxs:www.x-washer.com/mqtt', options);
    client = mqtt.connect(url, options);
    client.on('reconnect', (error) => {
      //that.setData({connectFlag:false})
      console.log('正在重连:', error)
    });
    client.on('connect', (e) => {
      console.log('成功连接服务器111')
      client.publish(that.data.RX, "{SQLID}");
      //订阅一个主题
      client.subscribe(this.data.TX, {
        qos: 1
      }, function (err) {
        if (!err) {
          
          console.log("订阅成功")
          console.log("写入数据："+that.data.RX)
          client.publish(that.data.RX, "{SQLID}");
        }

      })
    })
    client.on('error', (error) => {
      that.setData({connectFlag:false})
      console.log('连接失败:', error)
    })

    //监听mq的返回
    client.on('message', function (topic, message, packet) {
      console.log("packet===="+packet.payload.toString())
      var data=packet.payload.toString();
      var mydata=data.replace("[{","[");
      mydata=mydata.replace('"id:"','"id":"');
      var obj = JSON.parse(mydata);
      that.setData({connectFlag:true});
      //client.end()
    })
  },
})
